;(function($){
	var Tip = function(){
		this.data = {};
		this.options = null;
		return this;
	};
	Tip.prototype.htmlBuilder = function(_this,data){
		var item = "<div class='ajaxload-select-item' index='{index}'>{showFeild}</div>		\n";
		var html = "";
		for(i in data){
			var itemTemp = item.replace("{index}",i).replace("{showFeild}",data[i][this.options.showFeild])
			;
			html = html+itemTemp;
		}
		var inputName = $(_this).attr("name");
		var boxClass = 's-item-box-'+inputName;
		html = "<div class='"+boxClass+"'>\n"+html+"</div>";
		$html = $(html);
		this.htmlRender(_this, html);
		return boxClass;
	};
	Tip.prototype.htmlRender = function(e,$html){
		if($html){
			$(e).popover('close');
			$(e).popover('setContent', $html);
			$(e).popover('open');
		}
    };
	Tip.prototype.selectItemEvent = function(_this,boxClass,opts){
		var _tipe = this;
		$(".ajaxload-select-item").unbind();
		$('.'+boxClass).find(".ajaxload-select-item").click(function(){
			var i = $(this).attr("index");
    		var data = _tipe.data[_tipe.currentValue][i];
    		_tipe.options.selectEvent(data,_this,_tipe.options);
    		$(_this).popover('close');
		});
    };
	
	
	var defaults = {url:"",
				searchFeild:'key',
				showFeild:'key',
				selectEvent:function(data,_this,options){
				$(_this).val(data[options.showFeild]);
			  }
			};
	
	var objCopy = function(desc,org){
		for(i in org){
			desc[i] = org[i];
		}
	}
	$.fn.inputLoad = function(opts){
		this.each(function(){
			opts = $.extend(defaults, opts);
			var options = {};
			objCopy(options,opts);
			var _this = this;
	        $(_this).bind('input propertychange', function(){
	        	var tip = new Tip();
	        	tip.options = options;
	        	var inputValue=$(this).val();
	        	var postData = {};
	        	postData[options.searchFeild] = inputValue;
	        	$.post(options.url,postData,function(obj){
	        		obj = JSON.parse(obj);
	        		if(obj.success){
	        			tip.data[inputValue] = obj.data;
	        			if(obj.data.length==0){
	        				return;
	        			}
	        			tip.currentValue = inputValue;
	        			var boxClass = tip.htmlBuilder(_this,tip.data[inputValue]);
	        			tip.selectItemEvent(_this,boxClass);
	        		}
	        	});
	        	
	        });
		});
	};
})(jQuery);